package com.example.springsecurity.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springsecurity.domain.Declare;
import com.example.springsecurity.domain.LoginUser;
import com.example.springsecurity.domain.SysUser;
import com.example.springsecurity.security.SecurityUtils;
import com.example.springsecurity.security.User;
import com.example.springsecurity.service.CollegeService;
import com.example.springsecurity.service.RoleService;
import com.example.springsecurity.service.SysUserService;
import com.example.springsecurity.utils.FileUploadAndDownload;
import com.example.springsecurity.utils.ResultBean;
import com.example.springsecurity.utils.convert.Convert;
import com.example.springsecurity.utils.excel.ExcelUtils;
import com.example.springsecurity.utils.ifnull.StringUtils;
import com.example.springsecurity.utils.redis.RedisCache;
import com.example.springsecurity.utils.sendMessage.SendMail;
import com.example.springsecurity.utils.token.TokenUtil;
import com.example.springsecurity.utils.verfycode.VerifyCodeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * @ClassName LoginController
 * @Description TODO   用户登录接口:login
 *   注册时邮箱验证码的发送：registerEmail
 *   注册：register
 *   验证用户名是否存在：verifyUserName
 *   验证手机号是否存在：verifyPhone
 *   验证邮箱是否存在：verifyEmail
 *   找回密码发送邮箱验证码：sendEmail
 *   找回密码：updatePassword
 *   管理员添加用户：addUser
 *   停用用户：disabledUser
 *   删除用户：deleteUser
 *   用户信息修改：updateUser
 *   修改头像：updateAvatar
 *   下载导入模板：getTemplate
 *   导入用户: importSysUser
 *   查询全部用户信息：getAllUser
 *   导出用户信息: export
 * @Author lvyongwei
 * @Date 2020-09-25 17：15
 **/
@Controller
@RequestMapping("/user")
public class LoginController {

    /**
     * 验证码 redis key
     */
    public static final String CAPTCHA_CODE_KEY = "captcha_codes:";

    /**
     * 邮箱找回密码验证码 redis key
     */
    public static final String EMAIL_VERIFICATION_CODE = "email_codes:";

    /**
     * 邮箱注册验证码 redis key
     */
    public static final String EMAIL_REGISTER_CODE = "register_email_codes:";

    /**
     * redis工具
     */
    @Autowired
    private RedisCache redisCache;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * token工具
     */
    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private SysUserService sysUserService;

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 文件上传下载工具类
     */
    @Autowired
    private FileUploadAndDownload fileUploadAndDownload;

    /**
     * 导入导出工具类
     */
    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private RoleService roleService;

    @Autowired
    private CollegeService collegeService;

    /**
     * 用户登录
     * @param loginUser 用来接收前端传来的信息
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultBean login(@RequestBody LoginUser loginUser){
       /* String verifyKey = CAPTCHA_CODE_KEY+loginUser.getUuid();
        *//**
         * 获取redis中的存储的验证码信息
         *//*
        String captcha = redisCache.getCacheObject(verifyKey);
        //删除对象
        redisCache.deleteObject(verifyKey);
        if(captcha == null){
            return ResultBean.error("验证码已失效");
        }
        if(!captcha.equalsIgnoreCase(loginUser.getVerfyCode())){
            return ResultBean.error("验证码错误");
        }*/
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUserName(), loginUser.getPassword()));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                logger.error(e.getMessage());
                return ResultBean.error("用户不存在/密码错误");
            }
            else if(e instanceof UsernameNotFoundException)
            {
                logger.error(e.getMessage());
                return ResultBean.error("用户不存在，登陆失败");
            }else{
                logger.error(e.getMessage());
                return ResultBean.error(e.getMessage());
            }
        }
        /**
         * 获取用户主体
         */
        User user = (User) authentication.getPrincipal();
        String token = tokenUtil.createToken(user);
        /**
         * 获取登录用户信息
         */
        SysUser sysUser = user.getSysUser();
        sysUser.setPassword(null);
        ResultBean resultBean = new ResultBean();
        resultBean.put("data",sysUser);
        resultBean.put("msg","登陆成功");
        resultBean.put("token",token);
        resultBean.put("code",200);
        return resultBean;
    }


    /**
     * 注册用户发送邮箱验证码
     * @param email
     * @return
     */
    @PostMapping("/registerEmail")
    @ResponseBody
    public ResultBean registerEmail(@RequestBody String email){
        JSONObject jsonObject = JSON.parseObject(email);
        /**
         * 获取邮件地址
         */
        String mail=jsonObject.getString("email");
        /**
         * 随机获取四位字符
         */
        String uuid = VerifyCodeUtils.generateVerifyCode(6);
        /**
         * 发送邮件
         */
        boolean flag = SendMail.sendMail(mail,"注册用户","您好，您注册用户的验证码为："+uuid);
        if(flag){
            redisCache.setCacheObject(EMAIL_REGISTER_CODE+mail,uuid,3, TimeUnit.MINUTES);
            return ResultBean.success("验证邮件发送成功");
        }
        return ResultBean.error("验证邮件发送失败");
    }


    /**
     * 用户注册
     * @param sysUser 系统用户实体
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public ResultBean register(@RequestBody SysUser sysUser){
        /**
         * 获取邮箱
         */
        String email = sysUser.getEmail();
        if(StringUtils.isNull(email)){
            return ResultBean.error("请输入邮箱号码");
        }
        //获取redis中存放的验证码
        String code = redisCache.getCacheObject(EMAIL_REGISTER_CODE + email);
        if(StringUtils.isNull(code)){
            return ResultBean.error("验证码已过时");
        }
        if(!sysUser.getRegisterCode().equalsIgnoreCase(code)){
            return ResultBean.error("验证码不正确");
        }else{
            if(!StringUtils.isNull(sysUserService.verifyUserName(sysUser.getUserName()))){
                return ResultBean.error("用户名已存在");
            }
            if(!StringUtils.isNull(sysUserService.verifyEmail(sysUser.getEmail()))){
                return ResultBean.error("邮箱已存在");
            }
            /**
             * 密码加密
             */
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
            try{
                /**
                 * 用户注册就只能是学生身份
                 */
                Integer[] roles = {5};
                sysUser.setRoleIds(roles);
                sysUserService.insertSysUser(sysUser);
                return ResultBean.success("注册用户成功,请登陆");
            }catch (Exception e){
                logger.error(sysUser.getUserName() + "用户注册失败" + new Date());
                return ResultBean.error("注册用户失败");
            }
        }
    }


    /**
     * 验证用户名是否存在
     * @param userName  用户名
     * @return
     */
    @GetMapping("/verifyUserName")
    @ResponseBody
    public ResultBean verifyUserName(String userName){
        /**
         * 根据用户名查询对象
         */
        SysUser user = sysUserService.verifyUserName(userName);
        /**
         * 判断用户名是否存在
         */
        if(StringUtils.isNotNull(user)){
            return ResultBean.error("用户名已存在");
        }
        return ResultBean.success("用户名可以注册");
    }


    /**
     * 验证手机号是否存在
     * @param phone  用户名
     * @return
     */
    @GetMapping("/verifyPhone")
    @ResponseBody
    public ResultBean verifyPhone(String phone){
        /**
         * 根据用户名查询对象
         */
        SysUser user = sysUserService.verifyPhone(phone);
        /**
         * 判断用户名是否存在
         */
        if(StringUtils.isNotNull(user)){
            return ResultBean.error("手机号已存在");
        }
        return ResultBean.success("手机号可以添加");
    }


    /**
     * 验证邮箱是否存在
     * @param email  用户名
     * @return
     */
    @GetMapping("/verifyEmail")
    @ResponseBody
    public ResultBean verifyEmail(String email){
        /**
         * 根据用户名查询对象
         */
        SysUser user = sysUserService.verifyEmail(email);
        /**
         * 判断用户名是否存在
         */
        if(StringUtils.isNotNull(user)){
            return ResultBean.error("邮箱已存在");
        }
        return ResultBean.success("邮箱可以添加");
    }


    /**
     * 找回密码发送邮箱验证码
     * @param email
     * @return
     */
    @PostMapping("/sendEmail")
    @ResponseBody
    public ResultBean sendEmail(@RequestBody String email){
        JSONObject jsonObject = JSON.parseObject(email);
        /**
         * 获取邮件地址
         */
        String mail=jsonObject.getString("email");
        /**
         * 随机获取四位字符
         */
        String uuid = VerifyCodeUtils.generateVerifyCode(6);
        //验证是否数据库有此邮箱
        SysUser sysUser = sysUserService.verifyEmail(mail);
        if(StringUtils.isNull(sysUser) || sysUser == null){
            return ResultBean.error("您输入的邮箱不存在");
        }
        /**
         * 发送邮件
         */
        boolean flag = SendMail.sendMail(mail,"找回密码邮件","你好，你找回密码的验证码是："+uuid);
        if(flag){
            redisCache.setCacheObject(EMAIL_VERIFICATION_CODE+mail,uuid,3, TimeUnit.MINUTES);
            return ResultBean.success("验证邮件发送成功");
        }
        return ResultBean.error("验证邮件发送失败");
    }


    /**
     * 找回密码
     * @param data  json字符串   userName、password、verifyCode、email
     * @return
     */
    @PostMapping("/updatePassword")
    @ResponseBody
    public ResultBean updatePassword(@RequestBody String data){
        /**
         * 解析json字符串
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String email = jsonObject.getString("email");
        String verifyCode = jsonObject.getString("verifyCode");
        String userName = jsonObject.getString("userName");
        /**
         * 加密字符串
         */
        String password = SecurityUtils.encryptPassword(jsonObject.getString("password"));
        /**
         * 判断
         */
        SysUser sysUser = sysUserService.verifyEmail(email);
        if(StringUtils.isNull(sysUser) || sysUser == null){
            return ResultBean.error("您输入的邮箱不存在");
        }
        if(!sysUser.getUserName().equals(userName)){
            return ResultBean.error("输入的邮箱和用户名不匹配");
        }
        //获取redis中存放的验证码
        String code = redisCache.getCacheObject(EMAIL_VERIFICATION_CODE + email);
        if(StringUtils.isNull(code)){
            return ResultBean.error("验证码已过时");
        }
        if(!verifyCode.equalsIgnoreCase(code)){
            return ResultBean.error("验证码不正确");
        }else{
            try{
                /**
                 * 密码修改
                 */
                sysUserService.updatePassword(email,password);
                /**
                 * 删除redis中存储的验证码
                 */
                redisCache.deleteObject(EMAIL_VERIFICATION_CODE + email);
                return ResultBean.success("修改密码成功，请重新登录");
            }catch (Exception e){
                return ResultBean.error("修改密码失败");
            }
        }
    }


    /**
     * 管理员添加用户
     * @param sysUser
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:add')")
    @PostMapping("/addUser")
    @ResponseBody
    public ResultBean addUser(@RequestBody SysUser sysUser){
        if(!StringUtils.isNull(sysUserService.verifyUserName(sysUser.getUserName()))){
            return ResultBean.error("用户名已存在");
        }
        if(!StringUtils.isNull(sysUserService.verifyEmail(sysUser.getEmail()))){
            return ResultBean.error("邮箱已存在");
        }
        if(!StringUtils.isNull(sysUserService.verifyPhone(sysUser.getPhone()))){
            return ResultBean.error("手机号已存在");
        }
        if(StringUtils.isNull(sysUser.getPassword()) || sysUser.getPassword() == null){
            sysUser.setPassword("123456");
        }
        /**
          * 密码加密
         */
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        try{
            sysUserService.insertSysUser(sysUser);
            return ResultBean.success("添加用户成功");
        }catch (Exception e){
            logger.error(sysUser.getUserName() + "用户添加失败" + new Date());
            return ResultBean.error("添加用户失败");
        }
    }


    /**
     * 停用用户
     * @param data   {"userIds":[1,2,3]}
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:disabled')")
    @PostMapping("/disabledUser")
    @ResponseBody
    public ResultBean disabledUser(@RequestBody String data){
        /**
         * 解析用户id数组
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String array = jsonObject.getString("userIds");
        String userId = array.substring(1,array.length()-1);
        /**
         * 获取数组
         */
        Long[] userIds = Convert.toLongArray(",",userId);
        try{
            sysUserService.changeUserStatus(userIds,2);
            return ResultBean.success("停用用户成功");
        }catch (Exception e){
            return ResultBean.error("停用用户失败");
        }
    }


    /**
     * 重新启用用户
     * @param data   {"userIds":[1,2,3]}
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:disabled')")
    @PostMapping("/startUsingUser")
    @ResponseBody
    public ResultBean startUsingUser(@RequestBody String data){
        /**
         * 解析用户id数组
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String array = jsonObject.getString("userIds");
        String userId = array.substring(1,array.length()-1);
        /**
         * 获取数组
         */
        Long[] userIds = Convert.toLongArray(",",userId);
        try{
            sysUserService.changeUserStatus(userIds,0);
            return ResultBean.success("启用用户成功");
        }catch (Exception e){
            return ResultBean.error("启用用户失败");
        }
    }


    /**
     * 删除用户
     * @param data  {"userIds":[1,2,3]}
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:delete')")
    @PostMapping("/deleteUser")
    @ResponseBody
    public ResultBean deleteUser(@RequestBody String data){
        /**
         * 解析用户id数组
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String array = jsonObject.getString("userIds");
        String userId = array.substring(1,array.length()-1);
        /**
         * 获取数组
         */
        Long[] userIds = Convert.toLongArray(",",userId);
        try{
            sysUserService.changeUserStatus(userIds,1);
            return ResultBean.success("删除用户成功");
        }catch (Exception e){
            return ResultBean.error("删除用户失败");
        }
    }


    /**
     * 用户信息修改
     * @param user
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:edit')")
    @PostMapping("/updateUser")
    @ResponseBody
    public ResultBean updateUser(@RequestBody SysUser user){
        try {
            /**
             * 判断是修改密码的话，密码加密
             */
            if(!StringUtils.isNull(user.getPassword())){
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            }
            /**
             * 判断邮箱，手机号是否存在
             *     如果验证邮箱存在，但是该邮箱属于用户的id跟修改id不同，则判断存在不允许修改
             */
            SysUser sysUser = sysUserService.verifyEmail(user.getEmail());
            if(!StringUtils.isNull(sysUser)){
                if(!StringUtils.isNull(sysUser) && user.getUserId().longValue()!=sysUser.getUserId().longValue()){
                    return ResultBean.error("邮箱已存在");
                }
            }
            SysUser sysUser1 = sysUserService.verifyPhone(user.getPhone());
            if(!StringUtils.isNull(sysUser1)){
                if(!StringUtils.isNull(sysUser1) && user.getUserId().longValue()!=sysUser1.getUserId().longValue()){
                    return ResultBean.error("手机号已存在");
                }
            }
            sysUserService.updateSysUser(user);
            return ResultBean.success("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("修改失败");
        }
    }


    /**
     * 修改头像
     * @param file
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:updateAvatar')")
    @PostMapping("/updateAvatar")
    @ResponseBody
    public ResultBean updateAvatar(MultipartFile file,Long userId){
        /**
         * 判断是否为空，并上传文件
         */
        String fileName = fileUploadAndDownload.upload2(file,"avatar\\");
        /**
         * 创建系统用户对象
         */
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setAvatar(fileName);
        try{
            sysUserService.updateSysUser(sysUser);
            return ResultBean.success("用户修改头像成功",fileName);
        }catch (Exception e){
            return ResultBean.error("用户修改头像失败");
        }
    }


    /**
     * 下载导入模板
     * @param request
     * @param response
     */
    @GetMapping("/getTemplate")
    public void getTemplate(HttpServletRequest request, HttpServletResponse response){
        excelUtils.cooperation(request,response, SysUser.class,"用户导入模板");
    }


    /**
     * 导入用户
     * @param file  导入excel文件
     * @param sysUser   用户信息,  院系，专业，班级，角色数组
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:import')")
    @PostMapping("/importSysUser")
    @ResponseBody
    public ResultBean importSysUser(MultipartFile file,SysUser sysUser){
        return sysUserService.importSysUser(file,sysUser);
    }


    /**
     * 查询所有用户信息
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:user:look')")
    @PostMapping("/getAllUser")
    @ResponseBody
    public ResultBean getAllUser(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSON.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer collegeId = jsonObject.getInteger("collegeId");
        String userName = jsonObject.getString("userName");
        String role = jsonObject.getString("roleIds");
        String roles = role.substring(1,role.length()-1);
        Integer[] roleIds = Convert.toIntArray(",",roles);
        /**
         * 设置查询条件
         */
        SysUser sysUser = new SysUser();
        sysUser.setCollegeId(collegeId);
        sysUser.setRealName(userName);
        sysUser.setUserName(userName);
        sysUser.setRoleIds(roleIds);
        /**
         * 初始化页面信息
         */
        if(StringUtils.isNull(pageNum) || pageNum == 0){
            pageNum = 1;
        }
        if(StringUtils.isNull(pageSize) || pageSize == 0){
            pageSize = 10;
        }
        /**
         * 判断是否是学生,则获取学生身份用户
         */
        if(sysUser.getRoleIds()!=null && sysUser.getRoleIds().length == 1 && sysUser.getRoleIds()[0] == 5){
            try{
                //执行分页
                PageHelper.startPage(pageNum,pageSize);
                //根据type获取数据信息
                List<SysUser> dataSearches=sysUserService.getAllStudent(sysUser);
                //获取分页信息
                PageInfo<SysUser> pageInfo=new PageInfo<SysUser>(dataSearches);
                return ResultBean.success("获取学生信息成功",pageInfo);
            }catch (Exception e){
                e.printStackTrace();
                logger.error(e.getMessage());
                return ResultBean.error("获取学生信息失败");
            }
        }
        try{
            //执行分页
            PageHelper.startPage(pageNum,pageSize);
            //根据type获取数据信息
            List<SysUser> dataSearches=sysUserService.getAllSysUser(sysUser);
            //获取分页信息
            PageInfo<SysUser> pageInfo=new PageInfo<SysUser>(dataSearches);
            return ResultBean.success("获取教工信息成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return ResultBean.error("获取教工信息失败");
        }
    }


    /**
     * 导出用户信息
     * @param request
     * @param response
     */
    @GetMapping("/export")
    public void getAll(HttpServletRequest request,HttpServletResponse response,SysUser sysUser){
        List<SysUser> sysUsers = null;
        if(sysUser.getRoleIds()!=null && sysUser.getRoleIds().length == 1 && sysUser.getRoleIds()[0] == 5){
            sysUsers = sysUserService.getAllStudent(sysUser);
        }else{
            sysUsers = sysUserService.getAllSysUser(sysUser);
        }
        excelUtils.cooperationData(request,response,sysUsers,"用户信息",SysUser.class);
    }


    /**
     * 项目管理员添加申报项目
     * @param declare
     * @return
     */
    @PostMapping("/addDeclareProject")
    @ResponseBody
    public ResultBean addDeclareProject(@RequestBody Declare declare){
        SysUser sysUser=SecurityUtils.getLoginUser().getSysUser();
        logger.info("用户信息{}",sysUser);
        return sysUserService.addDeclareProject(declare);
    }


    /**
     * 项目管理员修改申报项目信息
     * @param declare
     * @return
     */
    @ResponseBody
    @PostMapping("/updateDeclareProject")
    public ResultBean updateDeclareProject(@RequestBody Declare declare){
        return sysUserService.updateDeclareProject(declare);
    }


    /**
     * 根据申报项目编号来获取
     * @param declareId
     * @return
     */
    @ResponseBody
    @GetMapping("/getDeclareProject")
    public ResultBean getDeclareProject(Integer declareId){
        return sysUserService.getDeclareProject(declareId);
    }


    /**
     * 获取申报项目列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @GetMapping("/getAllDeclareProject")
    public ResultBean getAllDeclareProject(Integer pageNum,Integer pageSize){
        return sysUserService.getAllDeclareProject(pageNum,pageSize);
    }


    /**
     * 判断这个短链接是否存在
     * @param declare
     * @return
     */
    @ResponseBody
    @PostMapping("/checkShortLink")
    public ResultBean checkShortLink(@RequestBody Declare declare){
        return sysUserService.checkShortLink(declare);
    }


    /**
     * 申报网站免登录
     * @param declare
     * @return
     */
    @ResponseBody
    @PostMapping("/avoidLogin")
    public ResultBean avoidLogin(@RequestBody Declare declare){
        return sysUserService.avoidLogin(declare);
    }


    /**
     * 删除申报案例
     * @param declareId
     * @return
     */
    @ResponseBody
    @GetMapping("/deleteDeclareProject")
    public ResultBean deleteDeclareProject(Integer declareId){
        return sysUserService.deleteDeclareProject(declareId);
    }


    /**
     * 获取用户信息
     * @param username
     * @return
     */
    @ResponseBody
    @GetMapping("/getDeclareProjectUser")
    public ResultBean getDeclareProjectUser(String username){
        return sysUserService.getDeclareProjectUser(username);
    }


    /**
     * 用户修改密码时验证密码是否正确
     * @return
     */
    @ResponseBody
    @PostMapping("/validatePassword")
    public ResultBean validatePassword(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String userName = jsonObject.getString("userName");
        String password = jsonObject.getString("password");
        /**
         * 获取用户信息
         */
        SysUser sysUser = sysUserService.getUserByUserName(userName);
        if(StringUtils.isNull(sysUser) || sysUser==null){
            return ResultBean.error("没有该用户信息");
        }
        if(SecurityUtils.matchesPassword(password,sysUser.getPassword())){
            return ResultBean.success("输入密码正确");
        }else{
            return ResultBean.error("输入密码错误");
        }
    }

    /**
     * 重置密码
     * @return
     */
    @ResponseBody
    @PostMapping("/resetPassword")
    public ResultBean resetPassword(@RequestBody SysUser sysUser){
        /**
         * 密码加密
         */
        String password = SecurityUtils.encryptPassword(sysUser.getPassword());
        sysUser.setPassword(password);
        try{
            sysUserService.resetPassword(sysUser);
            return ResultBean.success("修改密码成功");
        }catch (Exception e){
            return ResultBean.error("修改密码失败");
        }
    }
}
